import { login, logout, getInfo, getUserDetailById } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
const getDefaultState = () => {
  return {
    token: getToken() || null,
    userinfo: {},
    name: '',
    avatar: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
    setToken(token)
  },
  // 删除缓存
  removeToken (state) {
    state.token = ''
    removeToken()
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.userinfo.staffPhoto = avatar
  },
  set_userinfo: (state, userinfo) => {
    state.userinfo = userinfo
  },
  remove_userinfo: (state, userinfo) => {
    state.userinfo = {}
  }
}

const actions = {
  // 用户登录,保存token
  login ({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ mobile: username.trim(), password: password }).then(response => {
        const { data, success } = response
        if (success) {
          commit('SET_TOKEN', data)
          resolve()
        }
        // 网络请求失败的捕获
      }).catch(error => {
        // reject(error)错误对象
        reject(error)
      })
    })
  },

  // 获取用户资料
  getInfo (context, payload) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        const { data } = response
        getUserDetailById(data.userId).then(res => {
          const { data: data1 } = res
          context.commit('set_userinfo', { ...data, ...data1 })
        })
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  // user logout
  logout ({ commit, state }) {
    resetRouter()
    return new Promise((resolve, reject) => {
      // 清除token
      commit('removeToken')
      // 清除用户信息
      commit('remove_userinfo')
      // 清除添加的动态路由,防止重复添加
      resetRouter()
      commit('permission/setAsyncRouter', [], { root: true })
      resolve()
    })
  },

  // remove token
  resetToken ({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

